<template>
  <div class="app-container">
<!--    <div class="header">-->
<!--      <h2 style="margin: 0;">接口重试列表</h2>-->
<!--    </div>-->

    <div class="main-content">
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="请求ID" class="search-item">
            <el-input v-model="searchForm.requestId" placeholder="请输入请求ID" clearable />
          </el-form-item>
          <el-form-item label="接口URL" class="search-item">
            <el-input v-model="searchForm.memberApiUrl" placeholder="请输入接口URL" clearable />
          </el-form-item>
          <el-form-item label="请求body" class="search-item">
            <el-input v-model="searchForm.jsonData" placeholder="请输入请求body内容" clearable />
          </el-form-item>
          <el-form-item class="search-item">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          height="100%"
          v-loading="loading"
          :default-sort="{ prop: 'sendTime', order: 'descending' }"
        >
          <el-table-column prop="index" label="序号" width="40" align="center" />
          <el-table-column prop="requestId" label="请求ID" min-width="140" />
          <el-table-column prop="httpMethod" label="请求方式" min-width="60" />
          <el-table-column prop="sendTime" label="首次发送时间" sortable min-width="155" />
          <el-table-column prop="ysMessageId" label="消息ID" min-width="120" />
          <el-table-column prop="memberApiUrl" label="接口URL" min-width="200" />
          <el-table-column prop="jsonData" label="请求body" min-width="300">
            <template slot-scope="scope">
              <el-popover placement="top-start" width="500" trigger="hover" popper-class="custom-popover">
                <div class="popover-content">
                  <el-button class="copy-btn" size="mini" type="primary" @click="copyToClipboard(scope.row.jsonData)">
                    复制
                  </el-button>
                  <div class="popover-text">
                    {{ formatJsonForDisplay(scope.row.jsonData) }}
                  </div>
                </div>
                <div class="json-cell" slot="reference">
                  {{ formatJsonForDisplay(scope.row.jsonData) }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="msgDesc" label="业务类型" min-width="100" />
          <el-table-column prop="responseMessage" label="响应结果" min-width="200">
            <template slot-scope="scope">
              <el-popover placement="top-start" width="500" trigger="hover" popper-class="custom-popover">
                <div class="popover-content">
                  <el-button class="copy-btn" size="mini" type="primary" @click="copyToClipboard(scope.row.responseMessage)">
                    复制
                  </el-button>
                  <div class="popover-text">
                    {{ formatJsonForDisplay(scope.row.responseMessage) }}
                  </div>
                </div>
                <div class="json-cell" slot="reference">
                  {{ formatJsonForDisplay(scope.row.responseMessage) }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="retryTimes" label="重试次数" width="55" align="center" />
          <el-table-column prop="sendStatus" label="发送状态" width="70" align="center" class-name="status-cell" />
          <el-table-column label="操作" width="180" align="center" class-name="operation-cell" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="primary" @click="handleSend(scope.$index, scope.row)">发送</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑请求数据" :visible.sync="dialogVisible" width="80%">
      <el-input type="textarea" v-model="editForm.jsonData" class="json-editor" :autosize="{ minRows: 15 }" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRetryList, updateRetryData, resendRetry } from '@/api/apilog/apilog';

export default {
  name: 'DataList',
  data() {
    return {
      tableData: [],
      loading: false,
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      searchForm: {
        requestId: '',
        memberApiUrl: '',
        jsonData: '',
      },
      dialogVisible: false,
      editForm: {
        requestId: '',
        jsonData: '',
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      const params = {
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        requestId: this.searchForm.requestId,
        memberApiUrl: this.searchForm.memberApiUrl,
        jsonData: this.searchForm.jsonData,
      };

      try {
        const response = await getRetryList(params);
        this.tableData = response.data.list.map((item, index) => ({
          ...item,
          index: index + 1 + (this.pagination.pageNo - 1) * this.pagination.pageSize,
          sendTime: this.formatTime(item.sendTime),
        }));
        this.pagination.total = response.data.total;
      } catch (error) {
        this.$message.error(error.message || '获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    formatJsonForDisplay(json) {
      if (!json) return '';
      try {
        const parsed = typeof json === 'string' ? JSON.parse(json) : json;
        return JSON.stringify(parsed, null, 2);
      } catch (e) {
        return json;
      }
    },

    copyToClipboard(text) {
      let textToCopy;
      try {
        const jsonObj = typeof text === 'string' ? JSON.parse(text) : text;
        textToCopy = JSON.stringify(jsonObj, null, 2);
      } catch (e) {
        textToCopy = text;
      }
      const textarea = document.createElement('textarea');
      textarea.value = textToCopy;
      textarea.style.position = 'fixed';
      textarea.style.left = '0';
      textarea.style.top = '0';
      textarea.style.opacity = '0';
      document.body.appendChild(textarea);
      textarea.select();

      try {
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('格式化JSON已复制到剪贴板');
        } else {
          this.$message.error('复制失败');
        }
      } catch (err) {
        this.$message.error('复制失败: ' + err);
      }

      document.body.removeChild(textarea);
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.pagination.pageNo = val;
      this.fetchData();
    },

    handleEdit(index, row) {
      this.editForm = {
        requestId: row.requestId,
        jsonData: typeof row.jsonData === 'object' ? JSON.stringify(row.jsonData, null, 2) : row.jsonData,
      };
      this.dialogVisible = true;
    },

    async saveEdit() {
      if (!this.editForm.jsonData.trim()) {
        this.$message.warning('请求数据不能为空');
        return;
      }

      try {
        await updateRetryData({
          jsonData: this.editForm.jsonData,
          requestId: this.editForm.requestId,
        });
        this.$message.success('保存成功');
        this.dialogVisible = false;
        this.fetchData();
      } catch (error) {
        this.$message.error(error.message || '保存失败');
      }
    },

    handleSend(index, row) {
      this.$confirm('确定要重新发送此请求吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            await resendRetry(row.requestId);
            this.$message.success('发送成功');
            this.fetchData();
          } catch (error) {
            this.$message.error(error.message || '发送失败');
          }
        })
        .catch(() => {
          this.$message.info('已取消发送');
        });
    },

    handleSearch() {
      this.pagination.pageNo = 1;
      this.fetchData();
    },

    resetSearch() {
      this.searchForm = {
        requestId: '',
        memberApiUrl: '',
        jsonData: '',
      };
      this.handleSearch();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  width: 90vw;
  height: 90vh;
  display: flex;
  flex-direction: column;

  .header {
    padding: 15px 20px;
    background: #f5f7fa;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 10;
  }

  .main-content {
    flex: 1;
    padding: 0 20px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .search-container {
      padding: 15px 0;
      background: #fff;
      margin-bottom: 10px;
      border-radius: 4px;

      .search-form {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
      }

      .search-item {
        margin-right: 15px;
        margin-bottom: 10px;
      }
    }

    .table-wrapper {
      flex: 1;
      overflow: hidden;
      position: relative;

      .el-table {
        width: 100% !important;

        ::v-deep .el-table__header-wrapper {
          position: sticky;
          top: 0;
          z-index: 10;
          background: white;
        }

        ::v-deep .el-table__body-wrapper {
          overflow-y: auto;
        }

        ::v-deep .cell {
          white-space: pre-line;
          word-break: break-all;
        }

        .json-cell {
          max-width: 400px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          cursor: pointer;
        }
      }
    }

    .pagination {
      margin: 20px 0;
      text-align: right;
      flex-shrink: 0;
    }
  }

  .json-editor {
    width: 100%;

    ::v-deep .el-textarea__inner {
      font-family: Consolas, Monaco, monospace;
      min-height: 300px;
    }
  }

  .operation-cell {
    white-space: nowrap;
  }

  .status-cell {
    text-align: center;
  }
}

.custom-popover {
  max-width: 500px !important;
  max-height: 300px;
  overflow: auto;
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.5;
  padding: 10px;

  .popover-content {
    position: relative;

    .copy-btn {
      position: absolute;
      right: 5px;
      top: -30px;
      z-index: 10;
    }

    .popover-text {
      margin-top: 20px;
      padding-right: 40px;
    }
  }
}
</style>
